<?php
/*
  $Id: veyton4.base.php 410 2009-11-02 18:02:07Z dis $

  iclear design pattern
  Copyright (C) 2007 - 2009 iclear GmbH

                    All rights reserved.

  This program is free software licensed under the GNU General Public License (GPL).

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  USA

*************************************************************************/

  class IclearWrapperVeyton4 extends IclearWrapperBase {
    
    var $lang;
// iclear DMI -> added global order var
    var $code;
    
    var $title;
    
    var $description;
    
    var $enabled;
    
    var $order;
    
    var $orderStatusID;
    
    var $specialItemID = 0;
    
    var $showPriceTax;
    
    var $otPaymentItemID = 0;
    
    var $payment;
    
    var $db;
    
    var $addressKeysMask = array(
      'firstname' => '',
      'lastname' => '',
      'company' => '',
      'company_2' => '',
      'company_3' => '',
      'street_address' => 'info',
      'suburb' => '',
      'city' => '',
      'postcode' => '',
    );
    
// class constructor
    function IclearWrapperVeyton4(&$icCore) {
      $this->icVersion = '$Id: veyton4.base.php 410 2009-11-02 18:02:07Z dis $';
    	global $icCore, $db;
      $this->db =& $db;
      
    	parent::IclearWrapperBase($icCore);
    	
      if(!defined('IC_WRAPPER_ID')) {
      	die("Wrapper base class Veyton4 not instantiated!\n");
      }
      $this->id = IC_WRAPPER_ID;
            
      $this->code = 'iclear';
      $lang =& $icCore->getLanguage();
      $this->title = preg_match('!/admin/!', $_SERVER['SCRIPT_FILENAME']) ? $lang->getParam('MODULE_TITLE_ADMIN')
                                                                          : $lang->getParam('MODULE_TITLE');
      $this->description =  $lang->getParam('DESCRIPTION');
      $this->sort_order =  $lang->getParam('SORT_ORDER');

      $this->lang =& $lang;
            
      $this->enabled = $this->enabled();
      
      $this->showPriceTax = (isset($_SESSION['customers_status']['customers_status_show_price_tax'])  && $_SESSION['customers_status']['customers_status_show_price_tax']) ? true : false;
    }
    
    function iclearTable() {
    	return DB_PREFIX . '_' . IC_TABLE_ORDERS;
    }
    
    function dbQuery($sql) {
      return $this->db->Execute($sql);
    }
    
    function dbQuote($val) {
    	return $this->db->qstr($val);
    }
    
    function dbFetchRecord($sql) {
      $rec = false;
      if($qry = $this->dbQuery($sql)) {
        $rec = $qry->fields;
      }
      return $rec;
    }
    
    function dbLastInsertID() {
      return $this->db->Insert_ID();
    }
    
    function title() {
      return preg_match('!/admin/!', $_SERVER['SCRIPT_FILENAME']) ? $this->lang->getParam('MODULE_TITLE_ADMIN')
                                                                  : $this->lang->getParam('MODULE_TITLE');
    }
    
    function enabled() {
      return true;
    }
    
    function sortOrder() {
      return defined('MODULE_PAYMENT_ICLEAR_SORT_ORDER') ? MODULE_PAYMENT_ICLEAR_SORT_ORDER : 0;
    }
    
    function getOrder() {
      return $_SESSION['cart'];
    }
    
    function currency() {
    	global $currency;

      $rv = '';
      if($currency) {
        $rv = $currency->code;
      } else {
      	
      }
      return $rv;
    }
    
    function orderItemCount() {
      $rv = 0;
      
      if($order =& $this->getOrder()) {
        $rv = sizeof($order->show_content);
      }
      return $rv;
    }
    
    function itemPrice($price = 0, $multiplier = 100, $precision = 0) {
    	$rv = 0;
      if(isset($price) && $price) {
        $neg = false;
// catch double rounding bug
        if(0 > $price) {
          $price *= -1;
          $neg = true;
        }
        $rv = (int) (string) round($price * $multiplier, $precision);
        if($neg) {
          $rv *= -1;
        }
      }
    	return $rv;
    }
    
    function nextOrderItem() {
      $item = false;
      $id = $this->currentProductID; 
    	if($order =& $this->getOrder()) {
        if($id < sizeof($order->show_content)) {
        	$tmpOrder = array_values($order->show_content);
          $product = $tmpOrder[$id++];
          $item[IC_SOAP_ITEM_NO] = $this->encodeUTF8($product['products_id']);
	        $item[IC_SOAP_ITEM_TITLE] = $this->encodeUTF8($product['products_quantity'] . ' x ' . $product['products_name']);
	
	        // bundling items to single article @ iclear
	        $item[IC_SOAP_ITEM_QTY] = 1;
	
	        $item[IC_SOAP_ITEM_PRICE_NET] = $this->itemPrice($product['products_final_price']['plain_otax']);	
	        $item[IC_SOAP_ITEM_PRICE_GROS] = $this->itemPrice($product['products_final_price']['plain']);	
	        $item[IC_SOAP_ITEM_VAT_RATE] = $this->itemPrice($product['products_tax_rate'], 1, 1);
	        if(!$item[IC_SOAP_ITEM_VAT_RATE]) {
	          $item[IC_SOAP_ITEM_VAT_RATE] = '0.0';
	        }
        }
        $this->currentProductID = $id;
      }
      return $item;
    }
    
    function specialItems() {
      $items = false;
      
      $order =& $this->getOrder();
// get shipping item
      if( $order && isset($order->show_sub_content)) {
      	$recSet = array_values($order->show_sub_content);
      	foreach($recSet AS $rec) {
      		$item = array();
	      	$item[IC_SOAP_ITEM_NO] = $this->specialItemID; // in osc exists no zero itemID
	        $item[IC_SOAP_ITEM_TITLE] = $this->encodeUTF8($rec['products_name']);
	        
	        $item[IC_SOAP_ITEM_PRICE_NET] = $this->itemPrice($rec['products_final_price']['plain_otax']);
	        $item[IC_SOAP_ITEM_PRICE_GROS] =  $this->itemPrice($rec['products_final_price']['plain']);
	        $item[IC_SOAP_ITEM_QTY] = $rec['products_quantity'];
	        $item[IC_SOAP_ITEM_VAT_RATE] = $rec['products_tax_value'];
          $items[] = $item;
      	}
      }
      return $items;
    }
    
    function &deliveryAddress() {
      $rv = false;
      
      if( isset($_SESSION['customer']) && isset($_SESSION['customer']->customer_shipping_address) ) {
       	$rec = $_SESSION['customer']->customer_shipping_address;
        $params = array(
          IC_SOAP_ADDRESS_SALUTATION => ($rec['customers_gender'] == 'm' ? 'Herr' : 'Frau' ), 
          IC_SOAP_ADDRESS_FIRSTNAME => $rec['customers_firstname'],
          IC_SOAP_ADDRESS_LASTNAME => $rec['customers_lastname'],
          IC_SOAP_ADDRESS_COMPANY => $rec['customers_company'],
          IC_SOAP_ADDRESS_STREET => $this->parseStreet($rec['customers_street_address']),
          IC_SOAP_ADDRESS_STREET_NO => $this->parseStreetNo($rec['customers_street_address']), 
          IC_SOAP_ADDRESS_ZIPCODE => $rec['customers_postcode'],
          IC_SOAP_ADDRESS_CITY => $rec['customers_city'],
          IC_SOAP_ADDRESS_COUNTRY => $rec['customers_country_code'],
        );
        $address =& $this->icCore->getObject('IclearAddress', $instance = true);
        if($address->address($params)) {
          $rv =& $address;
        }
      }
      return $rv;
    }
    
    function sessionID($sessionID = '') {
      return $sessionID ? session_id($sessionID) : session_id();
    }
    
    function customerID() {
      return isset($_SESSION['customer']) ? $_SESSION['customer']->customers_id : 0 ;
    }
    
    function shopID() {
      return defined('ICLEAR_IC_SHOP_ID') ? ICLEAR_IC_SHOP_ID : 0;
    }
    
    function languageISO() {
      global $language;
      
      $rv = '';
      if($language) {
        $rv = $language->code;
      } else {
      	$rv = 'de';
      }
      return $rv;
    }
    
    function httpHost($https = false) {
      $rv = '';
      if($https && ENABLE_SSL) {
        $rv = HTTPS_SERVER;
      } else {
        $rv = HTTP_SERVER;
      }
      return $rv;
    }
    
    function redirect($url = '') {
      if($url) {
        xtc_redirect($url);
        exit;
      }
    }
    
    function finalizeBasket() {
    	// not in use here
    	return true;
    }
    
    function storeOrder() {
    	die("Store order not implemented in enclosing instance!\n");
    }
    
// this function is called in calls from iclear server as initiator - shop environemnt only loaded throug config!
    
    function maskOrder() {
      $rc = false;
      $basket =& $this->icCore->getBasket();
      if($orderID = $basket->orderID()) {
        $lang = $this->getLanguage();
        $fields = false;
        foreach($this->addressKeysMask AS $key => $val) {
          $fields[] = 'delivery_'.$key . ' = ' . ($val == 'info' ? '"'.$lang->getParam('ORDER_WAITING').'"' : '"**********"');
        }
        if($fields) {
          $sql = 'UPDATE ' . TABLE_ORDERS . ' SET ' . implode(',', $fields) . ' WHERE orders_id = ' . $orderID . ' LIMIT 1';
          $rc = $this->dbQuery($sql);
        }
      }
      return $rc;
    }
    
    function unmaskOrder() {
      $rc = false;
      $basket = $this->icCore->getBasket();
      if($orderID = $basket->orderID()) {
      	$icLang = $this->icCore->getLanguage();
      	$icLang->setLanguage($basket->language());
        $address = $basket->shopData('customer');
        $fields = false;
        foreach(array_keys($this->addressKeysMask) AS $key) {
          $fields[] = 'delivery_'.$key . ' = ' . $this->dbQuote($address['customers_' . $key]);
        }
        if($fields) {
          $sql = 'UPDATE ' . TABLE_ORDERS . ' SET ' . implode(',', $fields) . ' WHERE orders_id = ' . $orderID . ' LIMIT 1';
          if($rc = $this->dbQuery($sql)) {
		        $xtOrder = new order($orderID);
          	$xtOrder->_updateOrderStatus(ICLEAR_ORDER_STATUS_COMPLETED, $icLang->getParam("ORDER_WAITING_ACCEPTED"), true, true);
          }
        }
      }
      return $rc;
    }
    
    function cancelOrder($orderID = 0) {
// TODO: what's about to check the order undo result (always true correct)?
      $rc = true;
      $orderID = (int) $orderID;
      
      if($orderID) {
      	$xtOrder = new order();
      	$xtOrder->_deleteOrder($orderID, true);
      }
      return $rc;
    }
    
    function shopURL() {
    	global $xtLink;
      $rv = '';
      $basket =& $this->icCore->getBasket();
      
      if($basket->orderAccepted()) {
        if($this->status == IC_ORDER_CANCEL) {
          return $xtLink->_link(array('page'=>'index'));
        } else {
          $rv = $xtLink->_link(array('page'=>'checkout', 'paction'=>'success', 'conn'=>'SSL'));
        }
      } else {
        $rv = $xtLink->_redirect($xtLink->_link(
                                                array('page'=>'checkout',
                                                      'paction'=>'payment',
                                                      'conn'=>'SSL',
                                                      'params' => 'error=TEXT_PAYMENT_IC_TRANSACTION_ERROR')
                                                )
                                               );
                                    
      }
      return $rv;
    }
    
    function cleanSession() {
      $_SESSION['cart']->_resetCart();
      unset($_SESSION['selected_shipping']);
      unset($_SESSION['selected_payment']);
    }
    
    function process() {
      $soap =& $this->icCore->getObject('IclearSOAP');
      $rc = $this->icCore->perform($soap, IC_SOAP_SENDORDER_METHOD);
      return $rc;
    }
  }

?>
